//
//  CartoonRecommendDetailViewController.m
//  Double
//
//  Created by 袁庆秋 on 15/5/23.
//  Copyright (c) 2015年 袁庆秋. All rights reserved.
//

#import "CartoonRecommendDetailViewController.h"
#import <AFNetworking.h>
#import "RecommentDetailModel.h"
#import "DetailView.h"
#import <UIImageView+WebCache.h>
#import "CartoonPublicModel.h"
#import "PublicDetailViewController.h"
#import "PublicImageView.h"
#import "IntroView.h"
//#import "EpisodeView.h"
#import "CartoonPlay.h"
#import "AnimationCollectDatabase.h"
#import "AnimationCollectModel.h"
#import "HistoryModel.h"
#import "HistoryDatabase.h"
#import "CartoonButton.h"
#import "MineViewController.h"
#import "WeiboSDK.h"
#import "MineViewController.h"
#import "AppDelegate.h"

@interface CartoonRecommendDetailViewController ()<UIGestureRecognizerDelegate, UIWebViewDelegate, UIAlertViewDelegate>


@property (nonatomic, retain) UIScrollView *scroll;
@property (nonatomic, retain) CartoonButton *button;


@end

#define kAppKey         @"1837158850"
#define kRedirectURI    @"http://www.sharesdk.cn"


@implementation CartoonRecommendDetailViewController


- (void)dealloc
{
    [_button release];
    [_lastup release];
    [_scroll release];
    [_dic release];
    [_episodeArray release];
    [_categoryArray release];
    [_fromSiteArray release];
    [_watchUserArray release];
    [_iD release];
    [super dealloc];
}




- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dic = [NSMutableDictionary dictionary];
        self.categoryArray = [NSMutableArray array];
        self.episodeArray = [NSMutableArray array];
        self.fromSiteArray = [NSMutableArray array];
        self.watchUserArray = [NSMutableArray array];
    }
    return self;
}

- (void)loadView
{
    [super loadView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self startConnection];
    self.navigationItem.title = self.titleName;
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
//收藏按钮
    self.button = [[CartoonButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [_button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithCustomView:_button];
    self.navigationItem.rightBarButtonItem = button1;
    self.button.CartoonID = self.iD;
    
    NSInteger myUID = [self.button.CartoonID integerValue];
    NSUserDefaults *myloginID = [NSUserDefaults standardUserDefaults];
    NSInteger uid = [[myloginID objectForKey:@"loginName"] integerValue];
    NSMutableArray *array = (NSMutableArray *)[AnimationCollectDatabase selectID:myUID UID:uid];
//设置收藏按钮图片
    if ([array count] == 0) {

        [self.button setImage:[UIImage imageNamed:@"soucang.jpg"] forState:UIControlStateNormal];
    }else{

        [self.button setImage:[UIImage imageNamed:@"soucanghou.jpg"] forState:UIControlStateNormal];
    }
    
    [_button release];
    [button1 release];
    
    //设置返回按钮
    UIButton *left = [UIButton buttonWithType:UIButtonTypeSystem];
    left.frame = CGRectMake(0, 0, 32, 32);
    [left setImage:[UIImage imageNamed:@"fanhui.png"] forState:UIControlStateNormal];
    [left addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:left];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    

    
}

- (void)backAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark 收藏点击事件

- (void)buttonAction:(id)sender
{
 
    
#pragma mark-
#pragma mark 判断是否已收藏
    NSUserDefaults *myLoginID = [NSUserDefaults standardUserDefaults];
    NSInteger myId = [self.button.CartoonID integerValue];
    NSInteger uid = [[myLoginID objectForKey:@"loginName"] integerValue];
    NSMutableArray *array = (NSMutableArray *)[AnimationCollectDatabase selectID:myId UID:uid];
    if ([array count] == 0 && [self.button.imageView.image isEqual:[UIImage imageNamed:@"soucang.jpg"]]) {
        if (![[myLoginID objectForKey:@"loginName"] length] == 0 && [[myLoginID objectForKey:@"state"]isEqualToString:@"登录"]) {

            [self.button setImage:[UIImage imageNamed:@"soucanghou.jpg"] forState:UIControlStateNormal];

        }
        

        NSUserDefaults *myLoginName = [[NSUserDefaults alloc]init];
#pragma mark -
#pragma mark 登陆姓名为空就跳到登陆界面
        if ([[myLoginName objectForKey:@"loginName"] length] == 0) {
            
            WBAuthorizeRequest *request = [WBAuthorizeRequest request];
            request.redirectURI = kRedirectURI;
            request.scope = @"all";
            request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
                                 @"Other_Info_1": [NSNumber numberWithInt:123],
                                 @"Other_Info_2": @[@"obj1", @"obj2"],
                                 @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
            [WeiboSDK sendRequest:request];
            
            //注册消息中心
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessage:) name:@"userInformation" object:nil];
            
        } else {
            
            NSInteger albumId = [self.iD integerValue];
            
            NSMutableArray *idArray = (NSMutableArray *)[AnimationCollectDatabase selectID:albumId];

            //取得所有为空
            if (idArray.count == 0) {
                NSLog(@"所有数组为空");
                //判断登录状态
                if ([[myLoginName objectForKey:@"state"]isEqualToString:@"登录"]) {
                    
                    NSInteger AnimationId = [self.iD integerValue];
                    NSString * AnimationName = [NSString stringWithFormat:@"%@",[self.dic objectForKey:@"name"]];
                    NSString * AnimationPic = [NSString stringWithFormat:@"%@",[self.dic objectForKey:@"cover"]];
                    
                    NSInteger uid = [[myLoginID objectForKey:@"loginName"] integerValue];
                    AnimationCollectModel * model = [AnimationCollectModel AnimationCollectModelWithAnimationId:AnimationId AnimationName:AnimationName AnimationPic:AnimationPic uid:uid idmin:AnimationId];
                    
                    [AnimationCollectDatabase insertWithModel:model];
                    
#pragma mark在这里是没有登陆
                }else{
                    MineViewController *loginNext = [[MineViewController alloc]init];
                    [self.navigationController pushViewController:loginNext animated:YES];

                }
                

#pragma mark -
#pragma mark这里得判断人和id()
            }else{
                //判断所有id号有没有使用
                NSString *myNewAlbumId = [NSString string];
                NSMutableString *countStr = [NSMutableString string];
                NSString *albumIdStr = [NSString string];
                [countStr appendFormat:@"%@",self.iD];
                for (AnimationCollectModel *model in idArray) {
                    for (int i = 0; i < 1000; i++) {
                        [countStr appendFormat:@"%d",360];
                        albumIdStr = [NSString stringWithFormat:@"%ld",model.AnimationId];
                        if (![albumIdStr isEqualToString:countStr] ) {
                            //取得没有使用的值
                            myNewAlbumId = [NSString stringWithString:countStr];
                            break;
                        }
                        
                    }
                    
                }
                NSLog(@"这里id数组不为空");
                NSMutableArray *myPersonArray = (NSMutableArray *)[AnimationCollectDatabase selectID:[self.iD integerValue] UID:[[myLoginID objectForKey:@"loginName"] integerValue]];
                //数组
                if (myPersonArray.count == 0) {
                    if ([[myLoginName objectForKey:@"state"]isEqualToString:@"登录"]) {
                        
                        NSInteger AnimationId = [self.iD integerValue];
                        NSString * AnimationName = [NSString stringWithFormat:@"%@",[self.dic objectForKey:@"name"]];
                        NSString * AnimationPic = [NSString stringWithFormat:@"%@",[self.dic objectForKey:@"cover"]];
                        
                        NSInteger uid = [[myLoginID objectForKey:@"loginName"] integerValue];
                        AnimationCollectModel * model = [AnimationCollectModel AnimationCollectModelWithAnimationId:[myNewAlbumId integerValue] AnimationName:AnimationName AnimationPic:AnimationPic uid:uid idmin:AnimationId];
                        
                        [AnimationCollectDatabase insertWithModel:model];
                        
                        
#pragma mark-
#pragma mark在这里是没有登陆
                    }else{
                        
                        MineViewController *loginNext = [[MineViewController alloc]init];
                        [self.navigationController pushViewController:loginNext animated:YES];

                    }
                    

                }else{
                    
                    NSLog(@"已收藏状态");
                    
                    
                }
                
            }
            
        }
        
    }else if([self.button.imageView.image isEqual:[UIImage imageNamed:@"soucanghou.jpg"]]){
//        [self.button setTitle:@"收藏" forState:UIControlStateNormal];
        [self.button setImage:[UIImage imageNamed:@"soucang.jpg"] forState:UIControlStateNormal];

        AnimationCollectModel *myid = [[AnimationCollectModel alloc]init];
        for (AnimationCollectModel *model in array) {
            myid = model;
        }
        [AnimationCollectDatabase deleteWithModel:myid];
        
    }
    
}






#pragma mark -
#pragma mark 数据请求
- (void)startConnection
{
    
    NSString *url = [NSString stringWithFormat:@"http://manhua.haomee.cn/?m=Api&ios=23&pad=0&a=getInfo&video_id=%@&uid=(null)", self.iD];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        self.dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.categoryArray = [self.dic objectForKey:@"categorys"];
        self.episodeArray = [self.dic objectForKey:@"episode"];
        self.fromSiteArray = [self.dic objectForKey:@"from_site"];
        self.watchUserArray = [self.dic objectForKey:@"watchUser"];
        
        //数据请求之后再铺设页面
        [self createTopView];
        [self createCenterView];
        [self createBottomView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

//接收消息
- (void)receiveMessage:(NSNotification *)noti
{
    MineViewController *mine = [[MineViewController alloc] init];
    NSDictionary *dic = noti.userInfo;

    NSString *imageName = [dic objectForKey:@"profile_image_url"];
    [mine.headerImageView sd_setImageWithURL:[NSURL URLWithString:imageName] placeholderImage:[UIImage imageNamed:@"wo.png"] options:SDWebImageRetryFailed];
    
    
    mine.nameLabel.text = [dic objectForKey:@"name"];
    
}


#pragma mark -
#pragma mark 铺设详情页面上半部分
- (void)createTopView
{
    DetailView *detail = [[DetailView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 4)];
    [self.view addSubview:detail];
    [detail release];
    
    //显示图片
    [detail.showImage sd_setImageWithURL:[NSURL URLWithString:[self.dic objectForKey:@"cover"]] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"] options:SDWebImageRetryFailed];
    
    //名称
    detail.titleLabel.text = [self.dic objectForKey:@"name"];
    //地区
    detail.positionLabel.text = [self.dic objectForKey:@"area"];
    //主演
    NSString *character = [self.dic objectForKey:@"character"];
    detail.categorysLabel.text = [NSString stringWithFormat:@"主演:%@", character];
    //更新时间
    NSString *time = [self.dic objectForKey:@"update_string"];
    detail.updateLabel.text = [NSString stringWithFormat:@"更新时间:%@", time];
    //更新至11集
    
    //更新至..集 / 已完结..集
    NSString *str = [self.dic objectForKey:@"cur_num"];
    //是否完结
    NSString *str1 = [self.dic objectForKey:@"is_over"];
    
    if ([str1 isEqualToString:@"1"]) {
        if ([str hasPrefix:@"已"]) {
            detail.totalNumLabel.text = str;
        } else {
            detail.totalNumLabel.text = [NSString stringWithFormat:@"已完结,共%@集", str];
        }
    } else if ([str1 isEqualToString:@"0"]) {
        if ([str hasPrefix:@"更新"]) {
            detail.totalNumLabel.text = str;
        } else {
            detail.totalNumLabel.text = [NSString stringWithFormat:@"更新至%@集", str];
        }
    }
    
    
    //评分
    NSInteger total_num = [[self.dic objectForKey:@"score_total_num"] integerValue];
    NSInteger person_num = [[self.dic objectForKey:@"score_person_num"] integerValue];
    NSString *score = [NSString stringWithFormat:@"%ld", total_num/person_num];
    detail.score.text = [NSString stringWithFormat:@"%@分", score];
    detail.score.textColor = [UIColor orangeColor];
    
    
    
    
    //立即观看按钮
    [detail.watchBtn addTarget:self action:@selector(watchAction:) forControlEvents:UIControlEventTouchUpInside];
    //分享按钮
    [detail.downLoadBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark -
#pragma mark 观看、分享按钮
- (void)watchAction:(id)sender
{
    //从数组里取出来选中集的信息
    NSDictionary *dic = [self.episodeArray objectAtIndex:0];
    //选中集的视频请求网址
    NSString *url = [dic objectForKey:@"mUrl"];
    CartoonPlay *play = [[CartoonPlay alloc] init];
    play.url = url;
    [self.navigationController pushViewController:play animated:YES];
    [play release];
    
    
    NSInteger HistoryId = [self.iD integerValue];
    NSString * HistoryName = [NSString stringWithFormat:@"%@",[self.dic objectForKey:@"name"]];
    NSString * HistoryPic = [NSString stringWithFormat:@"%@",[self.dic objectForKey:@"cover"]];
    HistoryModel * model = [HistoryModel HistoryModelWithHistoryId:HistoryId HistoryName:HistoryName HistoryPic:HistoryPic];
    [HistoryDatabase insertWithModel:model];

}


//分享
- (void)shareAction:(id)sender
{
    AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = kRedirectURI;
    authRequest.scope = @"all";
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare] authInfo:authRequest access_token:myDelegate.wbtoken];
    request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
}


#pragma mark -
#pragma mark 铺设中间“播放源”和“大家也在看”

- (void)createCenterView
{
//播放源
    UILabel *fromSiteLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, self.view.frame.size.height / 4 + 5, self.view.frame.size.width / 4, 40)];
    fromSiteLabel.text = @"播放源: ";
    [self.view addSubview:fromSiteLabel];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 4 + 10, self.view.frame.size.height / 4 + 5, 40, 40)];
    [button setImage:[UIImage imageNamed:@"youku.jpg"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(playFilmAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
//大家也在看
    UILabel *publicLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, self.view.frame.size.height / 4 + 50, self.view.frame.size.width / 3, 40)];
    publicLabel.text = @"大家也在看:";
    [self.view addSubview:publicLabel];
    
    for (int i = 0; i < self.watchUserArray.count; i++) {
        PublicImageView *showImage = [[PublicImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width / 3 + 10) + i * (self.view.frame.size.width / 15 * 2 - 2), self.view.frame.size.height / 4 + 50, 40, 40)];
        showImage.userInteractionEnabled = YES;
        showImage.clipsToBounds = YES;
        showImage.layer.cornerRadius = 20;
        
        showImage.dic= [self.watchUserArray objectAtIndex:i];
        NSString *imageString = [showImage.dic objectForKey:@"head_pic"];
        [showImage sd_setImageWithURL:[NSURL URLWithString:imageString] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"] options:SDWebImageRetryFailed];
        showImage.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [showImage addGestureRecognizer:tap];
        [self.view addSubview:showImage];
        
    }
}

#pragma mark -
#pragma mark 创建下面的介绍和播放界面
- (void)createBottomView
{
    UIButton *introBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 4 + 100, self.view.frame.size.width / 2, 30)];
    [introBtn setTitle:@"简介" forState:UIControlStateNormal];
    [introBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [introBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [introBtn setBackgroundColor:[UIColor lightGrayColor]];
    introBtn.alpha = 0.7;
    [introBtn addTarget:self action:@selector(introViewShow:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:introBtn];
    
    UIButton *epiBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2, self.view.frame.size.height / 4 + 100, self.view.frame.size.width / 2, 30)];
    [epiBtn setTitle:@"剧集列表" forState:UIControlStateNormal];
    [epiBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [epiBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [epiBtn setBackgroundColor:[UIColor lightGrayColor]];
    epiBtn.alpha = 0.7;
    [epiBtn addTarget:self action:@selector(episodeViewShow:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:epiBtn];
    
    self.introView = [[IntroView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2, self.view.frame.size.width, self.view.frame.size.height / 2)];
    

    [self.introView zidingyiScroll:[self.dic objectForKey:@"intro"]];
    
    self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2, self.view.frame.size.width, self.view.frame.size.height / 4 * 3 - 130)];
    
    [self.view addSubview:self.scroll];
    [self.view addSubview:self.introView];
}

- (void)introViewShow:(id)sender
{
    self.scroll.alpha = 0;
    self.introView.alpha = 1;
    [self.view insertSubview:self.introView aboveSubview:self.scroll];
}

- (void)episodeViewShow:(id)sender
{
    self.scroll.contentSize = CGSizeMake(self.view.frame.size.width, 40 * self.episodeArray.count / 4 + 50);
    [self.view insertSubview:self.scroll aboveSubview:self.introView];
    self.introView.alpha = 0;
    self.scroll.alpha = 1;
    self.scroll.backgroundColor = [UIColor whiteColor];
    

    
    NSInteger count = self.episodeArray.count;
    CGFloat width = self.view.frame.size.width / 5;
    for (int i = 0; i < count; i++) {
        UIButton *playBtn = [[UIButton alloc] initWithFrame:CGRectMake(10 + i % 4 *(width + 10), 20 + i / 4 * 40, width, 30)];
        [playBtn setTitle:[NSString stringWithFormat:@"第%d集", i + 1] forState:UIControlStateNormal];
        [playBtn.layer setBorderWidth:2.0f];
        playBtn.layer.cornerRadius = 5;
        [playBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [playBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
        playBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [playBtn setBackgroundColor:[UIColor whiteColor]];
        [playBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
        [playBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [playBtn addTarget:self action:@selector(playFilmBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        playBtn.tag = i + 1;
        [self.scroll addSubview:playBtn];
    }
}

#pragma mark -
#pragma mark 点击选集数，播放视频
- (void)playFilmBtnClick:(id)sender
{
    UIButton *btn = (UIButton *)sender;
//从数组里取出来选中集的信息
    NSDictionary *dic = [self.episodeArray objectAtIndex:btn.tag - 1];
//选中集的视频请求网址
    NSString *url = [dic objectForKey:@"mUrl"];
    CartoonPlay *play = [[CartoonPlay alloc] init];
    play.url = url;
    play.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:play animated:YES];
    [play release];

}



#pragma mark -
#pragma mark 点击播放源“优酷”图标，播放视频第一集
- (void)playFilmAction:(id)sender
{
    NSDictionary *dic = [self.episodeArray objectAtIndex:0];
    NSString *str = [dic objectForKey:@"mUrl"];
    CartoonPlay *play = [[CartoonPlay alloc] init];
    play.url = str;
    [self.navigationController pushViewController:play animated:YES];
    [play release];
}

#pragma mark -
#pragma mark 所有观众头像点击进入观众主页
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    
}

#warning 分享的内容
#pragma mark -
#pragma Internal Method

- (WBMessageObject *)messageToShare
{
    WBMessageObject *message = [WBMessageObject message];
    
    message.text = [NSString stringWithFormat:@"我正在用“漫吧”观看 %@ .海量高清动漫应有尽有，漫友们快来这里团聚吧！链接:%@", [self.dic objectForKey:@"name"], [[self.episodeArray objectAtIndex:0] objectForKey:@"mUrl"]];
    
    
    
    
    return message;
}



@end
